package br.brpv.silvestrin.vendas.mainactivity;

import android.app.*;
import android.content.*;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import br.brpv.silvestrin.vendas.R;

import br.brpv.silvestrin.vendas.domain.AddedItem;
import br.brpv.silvestrin.vendas.domain.Company;
import br.brpv.silvestrin.vendas.domain.Order;
import br.brpv.silvestrin.vendas.domain.User;
import br.brpv.silvestrin.vendas.listeners.TabListener;
import br.brpv.silvestrin.vendas.loginactivity.LoginActivity;
import br.brpv.silvestrin.vendas.util.ShowMessage;
import br.brpv.silvestrin.vendas.webservice.ServerDataCacheService;
import br.brpv.silvestrin.vendas.webservice.ServerConnection;

import java.util.ArrayList;

public class MainActivity extends Activity implements SavedOrdersFragment.OnEditOrderListener {
    public static final String NEW_ORDER_TAB = "NewOrder";
    public static final String STOCK_TAB = "Stock";
    public static final String SAVED_ORDERS_TAB = "SavedOrders";
    public static final String FINAL_CONSUMER_TAB = "FinalConsumer";

    private static final int NEW_ORDER_TAB_INDEX = 0;
    private static final int STOCK_TAB_INDEX = 1;
    private static final int SAVED_ORDERS_TAB_INDEX = 2;
    private static final int FINAL_CONSUMER_TAB_INDEX = 3;

    private static final String SAVE_NEW_ORDER_COMPANY_INDEX = "saveNewOrderCompanyIndex";
    private static final String SAVE_STOCK_COMPANY_INDEX = "saveStockCompanyIntex";
    private static final String SAVE_SAVED_ORDERES_COMPANY_INDEX = "saveSavedOrderesCompanyIndex";
    private static final String SAVE_FINAL_CONSUMER_COMPANY_INDEX = "saveFinalConsumerComanyIndex";
    private static final String SAVE_COMPANIES_LIST = "saveCompaniesList";

    private TabListener<NewOrderFragment> newOrderFragmentTabListener;
    private TabListener<StockFragment> stockFragmentTabListener;
    private TabListener<SavedOrdersFragment> savedOrdersFragmentTabListener;
    private TabListener<FinalConsumerFragment> finalConsumerFragmentTabListener;

    private ActionBar.Tab tNewOrder;
    private ActionBar.Tab tStock;
    private ActionBar.Tab tSavedOrders;
    private ActionBar.Tab tFinalConsumer;

    User user;

    private CompanyFragment currentFragment;

    private ServerDataCacheService mServerDataCacheBinder;
    private boolean mBound;

    public ArrayAdapter<Company> companiesList;
	private MenuItem menuChangeCompany;
    private ActionBar mActionBar;
    private static MenuItem refreshMenuItem;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getIntent().getExtras();
        user = extras.getParcelable(LoginActivity.USER_EXTRA);

        mActionBar = getActionBar();
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        mActionBar.setDisplayShowHomeEnabled(false);
        mActionBar.setDisplayShowTitleEnabled(false);

        tNewOrder = mActionBar.newTab().setText(R.string.menu_button_novo_pedido);
        tStock = mActionBar.newTab().setText(R.string.menu_button_estoque);
        tSavedOrders = mActionBar.newTab().setText(R.string.menu_button_pedidos_salvos);
        tFinalConsumer = mActionBar.newTab().setText(R.string.menu_button_consumidor_final);


        newOrderFragmentTabListener =
                new TabListener<NewOrderFragment>(this, MainActivity.NEW_ORDER_TAB, NewOrderFragment.class);
        newOrderFragmentTabListener.setUser(user);
        tNewOrder.setTabListener(newOrderFragmentTabListener);

        stockFragmentTabListener =
                new TabListener<StockFragment>(this, MainActivity.STOCK_TAB, StockFragment.class);
        stockFragmentTabListener.setUser(user);
        tStock.setTabListener(stockFragmentTabListener);

        savedOrdersFragmentTabListener =
                new TabListener<SavedOrdersFragment>(this, MainActivity.SAVED_ORDERS_TAB, SavedOrdersFragment.class);
        savedOrdersFragmentTabListener.setUser(user);
        tSavedOrders.setTabListener(savedOrdersFragmentTabListener);

        finalConsumerFragmentTabListener =
                new TabListener<FinalConsumerFragment>(this, MainActivity.FINAL_CONSUMER_TAB, FinalConsumerFragment.class);
        finalConsumerFragmentTabListener.setUser(user);
        tFinalConsumer.setTabListener(finalConsumerFragmentTabListener);

        mActionBar.addTab(tNewOrder);
        mActionBar.addTab(tStock);
        mActionBar.addTab(tSavedOrders);
        mActionBar.addTab(tFinalConsumer);


        companiesList = new ArrayAdapter<Company>(this, android.R.layout.simple_spinner_dropdown_item, new ArrayList<Company>());


        if (savedInstanceState != null) {
            mActionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));

            newOrderFragmentTabListener.setIndexSelectedCompany(savedInstanceState.getInt(SAVE_NEW_ORDER_COMPANY_INDEX, 0));
            stockFragmentTabListener.setIndexSelectedCompany(savedInstanceState.getInt(SAVE_STOCK_COMPANY_INDEX, 0));
            savedOrdersFragmentTabListener.setIndexSelectedCompany(savedInstanceState.getInt(SAVE_SAVED_ORDERES_COMPANY_INDEX, 0));
            finalConsumerFragmentTabListener.setIndexSelectedCompany(savedInstanceState.getInt(SAVE_FINAL_CONSUMER_COMPANY_INDEX, 0));

            loadSavedCompaniesList(savedInstanceState);
        } else {

        }

        //bind on ServerDataCacheService
        Intent intent = new Intent(this, ServerDataCacheService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        View v = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);


        if (v instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);

            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) {
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
        return ret;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            ServerDataCacheService.LocalBinder localBinder = (ServerDataCacheService.LocalBinder)iBinder;

            mServerDataCacheBinder = localBinder.getService();
            mBound = true;

            ArrayList<Company> companyList = mServerDataCacheBinder.getCompaniesList();
            if(companyList.isEmpty()) ServerConnection.getCompaniesList(MainActivity.this);
            else onGetCompaniesListResult(companyList);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
        outState.putInt(SAVE_NEW_ORDER_COMPANY_INDEX, newOrderFragmentTabListener.getIndexSelectedCompany());
        outState.putInt(SAVE_STOCK_COMPANY_INDEX, stockFragmentTabListener.getIndexSelectedCompany());
        outState.putInt(SAVE_SAVED_ORDERES_COMPANY_INDEX, savedOrdersFragmentTabListener.getIndexSelectedCompany());
        outState.putInt(SAVE_FINAL_CONSUMER_COMPANY_INDEX, finalConsumerFragmentTabListener.getIndexSelectedCompany());


        //ArrayList<Company> companyArray = new ArrayList<Company>();
        //for(int i = 0; i < companiesList.getCount(); i++) {
        //    companyArray.add(companiesList.getItem(i));
        //}

        //outState.putParcelableArrayList(SAVE_COMPANIES_LIST, companyArray);

        super.onSaveInstanceState(outState);
    }

    public void loadSavedCompaniesList(Bundle savedInstanceState){
        if(savedInstanceState != null) {
            ArrayList<Parcelable> savedArray = savedInstanceState.getParcelableArrayList(SAVE_COMPANIES_LIST);
            ArrayList<Company> companyArray = new ArrayList<Company>();
            if(savedArray != null) {
                for(Parcelable p: savedArray) {
                    companyArray.add((Company) p);
                }

                companiesList.addAll(companyArray);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.general_menu, menu);
        
        menuChangeCompany = menu.findItem(R.id.menu_change_company);
        refreshMenuItem =  menu.findItem(R.id.menu_refresh);

        return true;
    }

    private void setSelectedCompanyIndexToCurrentTab(int index){
        int tab = getActionBar().getSelectedNavigationIndex();

        if(tab == NEW_ORDER_TAB_INDEX){
            newOrderFragmentTabListener.setIndexSelectedCompany(index);
        } else if(tab == STOCK_TAB_INDEX){
            stockFragmentTabListener.setIndexSelectedCompany(index);
        } else if(tab == SAVED_ORDERS_TAB_INDEX) {
        	savedOrdersFragmentTabListener.setIndexSelectedCompany(index);
        } else if(tab == FINAL_CONSUMER_TAB_INDEX) {
            finalConsumerFragmentTabListener.setIndexSelectedCompany(index);
            

        }
        changeMenuCompanyName(index);
    }

    private void setCompanyToCurrentTab(int codCompany){
        int index = getActionBar().getSelectedNavigationIndex();

        if(currentFragment != null) currentFragment.setSelectedCompany(codCompany);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_launch_calc:

                Intent i = new Intent("org.openintents.action.CALCULATOR");
                try {
                    startActivity(i);
                } catch (Exception e) {
                    i = new Intent();
                    i.setClassName("com.android.calculator2",
                            "com.android.calculator2.Calculator");
                    try{
                        startActivity(i);
                    }catch (Exception e1) {
                        i = new Intent();
                        i.setClassName("com.sec.android.app.popupcalculator",
                                "com.sec.android.app.popupcalculator.Calculator");
                        try{
                            startActivity(i);
                        } catch (Exception e2){
                            ShowMessage.alertDialog(this, R.string.missing_calculator);
                        }
                    }
                }

                break;

            case R.id.menu_change_company:
                changeCompanyDialogShow();
                break;

            case R.id.menu_refresh:
                refresh();
                break;

            case R.id.menu_exit:
                finish();
                break;
        }
        return true;
    }
    
    private void refresh() {
    	if(currentFragment != null) currentFragment.refresh();
    }

    private void changeCompanyDialogShow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(R.string.change_company_dialog_title);

        builder.setSingleChoiceItems(companiesList, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            	Company selected = (Company)companiesList.getItem(i);
                int codCompany = new Integer(selected.getId());

                setSelectedCompanyIndexToCurrentTab(i);
                setCompanyToCurrentTab(codCompany);
                
                dialogInterface.dismiss();
            }
        });
        
        builder.create().show();
    }

    public void onGetCompaniesListError(){
        //TODO tratar erro ao perar lista de empresas
    }

    public void onGetCompaniesListResult(ArrayList<Company> arrayCompany){
        companiesList.clear();
        companiesList.addAll(arrayCompany);

        mServerDataCacheBinder.setCompaniesList(arrayCompany);
        int defaultCompany = mServerDataCacheBinder.getDefaultCompany();
        if(defaultCompany == -1) ServerConnection.getDefaultCompany(this, user.getId());
        else onGetDefaultCompanyResult(String.valueOf(defaultCompany));
    }

    public void onGetDefaultCompanyError() {

    }

    public void onGetDefaultCompanyResult(String defaultCompany) {
        Company aux;
        int companyId = new Integer(defaultCompany);
        mServerDataCacheBinder.setDefaultCompany(companyId);

        for (int i = 0; i < companiesList.getCount(); i++){
            aux = companiesList.getItem(i);
            if(aux.getCodCompany().compareTo(defaultCompany) == 0){

                newOrderFragmentTabListener.setIndexSelectedCompany(i);
                stockFragmentTabListener.setIndexSelectedCompany(i);
                savedOrdersFragmentTabListener.setIndexSelectedCompany(i);
                finalConsumerFragmentTabListener.setIndexSelectedCompany(i);

                setSelectedCompanyIndexToCurrentTab(i);
                setCompanyToCurrentTab(companyId);
            }
        }
    }

    public CompanyFragment getCurrentFragment() {
        return currentFragment;
    }

    public void setCurrentFragment(CompanyFragment currentFragment) {
        this.currentFragment = currentFragment;
    }

    private void changeMenuCompanyName(int index){
        if(menuChangeCompany != null){
            Company selected = getCompany(index);
            if(selected != null) {
            	menuChangeCompany.setTitle(selected.toString());               
            }
        }
    }

    public MenuItem getMenuChangeCompany() {
		return menuChangeCompany;
	}

	public Company getCompany(int index) {
		return (Company) companiesList.getItem(index);
	}

    @Override
    public void onEditOrderClick(Order order, ArrayList<AddedItem> addedItems) {
        NewOrderFragment newOrderFragment = newOrderFragmentTabListener.getmFragment();
        newOrderFragmentTabListener.setIndexSelectedCompany(getCompanyIndexById(order.getCompanyId()));
        mActionBar.setSelectedNavigationItem(NEW_ORDER_TAB_INDEX);
        newOrderFragment.setSelectedCompany(Integer.parseInt(order.getCompanyId()));
        newOrderFragment.setOrderToEdit(order, addedItems);
    }

    @Override
    public void onRemoveOrderClick(String orderId) {
        NewOrderFragment newOrderFragment = newOrderFragmentTabListener.getmFragment();
        if(newOrderFragment!=null) newOrderFragment.stopOrderRemovedInSaveScreen(orderId);

        FinalConsumerFragment finalConsumerFragment = finalConsumerFragmentTabListener.getmFragment();
        if(finalConsumerFragment != null) finalConsumerFragment.stopOrderRemovedInSaveScreen(orderId);
    }

    @Override
    public void onBackPressed() {
        //do nothing when back button is pressed
    }

    private int getCompanyIndexById(String companyId) {
        for(int i = 0; i < companiesList.getCount(); i++) {
            if(companiesList.getItem(i).getCodCompany().equals(companyId)) return  i;
        }
        return 0;
    }

    public static void setRefreshing(boolean refreshing) {
        if(refreshMenuItem == null) return;

        if(refreshing)
            refreshMenuItem.setActionView(R.layout.action_refresh_progress);
        else
            refreshMenuItem.setActionView(null);
    }

}